// 引入模块依赖
const jwt = require('jsonwebtoken');

// 签名，加密字段
const secret = 'huangyanwu'

let options = {
    // clockTolerance: 60*24*10,
    audience: "account",
    issuer: "https://login.someorganization/auth"
};
//生成token
exports.generateToken = function(data){
    // 随机生成一个时间戳
    let created = Math.floor(Date.now() / 1000);
    let token = jwt.sign({
        data: data, // 需要加密的用户信息
        exp: created + 60 * 60,// 设置token过期时间为1小时
    }, secret, options
    );
    return token;
}

// 退出过期处理
exports.overToken = function(data){
    // 随机生成一个时间戳
    let created = Math.floor(Date.now() / 1000);
    let token = jwt.sign({
            data: data, // 需要加密的用户信息
            exp: created, // 直接过期
        }, secret, options
    );
    return token;
}

// 校验token
exports.verifyToken = function(token) {
    let res;
    try {
        if(typeof(token) !== undefined){
            let result = jwt.verify(token, secret, options) || {};
            res = {
                data: result.data || {},
                bol: true
            };
        }
    } catch (err) {
        res = {
            data: err,
            bol: false
        };
    }
    return res;
}

